package com.guyaogg.gulimall.member.config;

import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 顾遥
 */
@Slf4j
@Configuration
public class GulimallFeignConfig {

    /**
     * feign 远程调用拦截器，在请求之前会对请求做出处理
     * @return
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return template -> {
            // 1.拿去源请求参数
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            // 老请求,并发情况下为空了？？？
            // 原因是 ThreadLocal ，老请求存储在本地线程的，线程不一样所有没有老请求数据了，让主线程传入。
            HttpServletRequest request = null;
            if (attributes != null) {
                request = attributes.getRequest();
            }
            // 2.同步源请求参数，主要 Cookie
            String cookie = null;
            if (request != null) {
                cookie = request.getHeader("Cookie");
            }
            // 给新请求同步了老请求的 Cookie
            template.header("Cookie", cookie);
            log.debug("拦截器重新加上了 Cookie");
        };
    }


}
